from . import admins_bp
from ...models import User
from ...helper import redirect_back
from flask import render_template, flash
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, BooleanField, PasswordField
from flask_login import login_user, current_user


class LoginForm(FlaskForm):
    account = StringField('用户')
    password = PasswordField('密码')
    remember = BooleanField('记住我')
    login_action = SubmitField('登录')


@admins_bp.route('/login', methods=['GET', 'POST'])
def auth_login():
    if current_user.is_authenticated:
        return redirect_back('admins.dashboard')
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(account=form.account.data).first()
        if not user:
            flash('用户不存在', 'error')
        elif user.check_password(form.password.data):
            login_user(user, remember=form.remember.data)
            return redirect_back('admins.dashboard')
        else:
            flash('用户不存在或密码错误', 'error')
    return render_template('auth_login.html', form=form)

